package com.example.book.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.book.entity.Book;
import com.example.book.mapper.BookMapper;
import com.example.book.api.dto.BookDTO;
import com.example.book.service.BookService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 继承ServiceImpl父类，可以调用里面的字段信息。
 * 继承BookService接口，实现接口方法。
 */
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    @Autowired
    private BookMapper bookMapper;

    @Override
    @Transactional
    public Long createBook(BookDTO bookDTO) {
        Book book = new Book(); // 创建Book对象
        BeanUtils.copyProperties(bookDTO, book); // BeanUtile是官方的工具类，将DTO对象复制给Book对象，避免字段冲突
//        baseMapper.insert(book);
        bookMapper.insertBookByXml(book);
        return book.getId();
    }

    @Override
    @Transactional
    public boolean updateBook(BookDTO bookDTO) {
        Book book = new Book();
        BeanUtils.copyProperties(bookDTO, book);
        bookMapper.updateBookByAnnotation(book);
        return updateById(book);
    }

    @Override
    @Transactional
    public boolean deleteBook(Long bookId) {
        return removeById(bookId);
    }

    @Override
    public BookDTO getBookById(Long bookId) {
        Book book = getById(bookId);
        if (book == null) {
            return null;
        }
        BookDTO bookDTO = new BookDTO();
        BeanUtils.copyProperties(book, bookDTO);
        return bookDTO;
    }

    @Override
    public List<BookDTO> listBooks() {
        List<Book> bookList = list();
        return bookList.stream().map(book -> {
            BookDTO bookDTO = new BookDTO();
            BeanUtils.copyProperties(book, bookDTO);
            return bookDTO;
        }).collect(Collectors.toList());
    }
}
